package com.roselism.mobilesafe.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.roselism.mobilesafe.R;
import com.roselism.mobilesafe.utils.HttpConnectionHelper;
import com.roselism.mobilesafe.utils.convert.Converter;
import com.roselism.mobilesafe.utils.convert.InputStreamStringConverter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import butterknife.Bind;
import butterknife.ButterKnife;


public class SplashActivity extends AppCompatActivity {

    public static final int CODE_READ_SUCCESS = 0;
    public static final int CODE_IO_ERROR = 1;
    public static final int CODE_JSON_ERROR = 2;
    public static final int CODE_ENTER_HOME = 3;

    private static final String TAG = "SplashActivity";
    private static final int DELAY = 2000;

    @Bind(R.id.bg_image) ImageView bgImage;
    @Bind(R.id.versionName) TextView versionName;
    @Bind(R.id.progressbar) ProgressBar progressbar;
    @Bind(R.id.download_text) TextView downloadText; // 下载提示

    private SharedPreferences mSharedPreferences;

    private int serverVersionCode; // 服务器端版本号
    private String serverVersionName; // 服务器端版本名称
    private String desc; // 版本描述
    private String downloadUrl;

    private int curVersionCode; // 当前版本号
    private String curVersionName; // 当前版本名称

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CODE_READ_SUCCESS:

                    if (curVersionCode < serverVersionCode) {  // 有新版本 并且 是自动升级 显示对话框
                        showUpdateDialog(); // 创建一张表，提示用户是否升级
                    } else
                        enterHome(); // 不是自动升级或没有新版本，直接进入主界面
                    break;

                case CODE_IO_ERROR:
                    Log.e(TAG, "handleMessage: -->" + "网络连接错误");
                    enterHome();
                    break;

                case CODE_JSON_ERROR:
                    Log.e(TAG, "handleMessage: -->" + "json文件解析错误");
                    enterHome();
                    break;

                case CODE_ENTER_HOME: // 进入主界面
                    enterHome();
                    break;
            }
        }
    };

    public void enterHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        checkForUpdate();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initEvent();
        initData();
    }

    /**
     * 初始化view
     */
    void initView() {
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        mSharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
        boolean isAutoUpdate = mSharedPreferences.getBoolean("auto_update", true); // 判断是否自动更新
        if (isAutoUpdate) // 如果开启了自动更新，则检查更新，没有则不检查更新
            checkForUpdate();
        else {
            readPackageVersionInfo();
            mHandler.sendEmptyMessageDelayed(CODE_ENTER_HOME, DELAY); // 延迟两秒钟后发送
        }
    }

    /**
     * 初始化事件
     */
    void initEvent() {

    }

    /**
     * 初始化data
     */
    void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        enterHome();
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 与服务器进行对比，查看是否能够更新
     */
    void checkForUpdate() {
        Log.i(TAG, "checkForUpdate: ");
        readPackageVersionInfo();
        readServerVersionInfo();
    }

    /**
     * 获取当前的versionName
     */
    void readPackageVersionInfo() {
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES); // 获取包的信息

            curVersionCode = info.versionCode; // 版本号
            curVersionName = info.versionName; // 版本名称
            versionName.setText(curVersionName); // 设置versionname

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取远程服务器的当前app的版本的信息
     */
    void readServerVersionInfo() {
        Log.i(TAG, "readServerVersionInfo: ");

        new Thread() {
            @Override
            public void run() {

                final long statTime = System.currentTimeMillis();

                Log.i(TAG, "run: ");
                Message msg = mHandler.obtainMessage();
//                msg.what = CODE_ENTER_HOME;

                // 构建一个HttpUrlConnection 的对象
                HttpConnectionHelper helper = new HttpConnectionHelper.Builder().
                        setRequestMethod(HttpConnectionHelper.POST_METHOD).
                        setConnectionTimeOut(2000).
                        setReadTimeOut(3000).
                        setPath("http://www.google.com").
                        build();

                //http://188.188.5.59:8080/update/root/update.json
                try {
                    Log.i(TAG, "run: try");
                    Log.i(TAG, "run: -->" + helper.responseCode());

                    if (helper.isResponseOk()) { // 响应码为200 ok
                        Converter<InputStream, String> converter = new InputStreamStringConverter(); // 创建一个流转字符串的转换器
                        InputStream inputStream = helper.getConnection().getInputStream(); // 获取输入流
                        String json = converter.convert(inputStream); // 获得json数据

                        Log.i(TAG, "run: --> json = " + json);
                        JSONObject jsonObject = new JSONObject(json); // 转换成json对象

                        serverVersionCode = jsonObject.getInt("versionCode"); // 服务器端的版本号
                        serverVersionName = jsonObject.getString("versionName");//服务器端的版本名称
                        desc = jsonObject.getString("description"); // 新版本的描述
                        downloadUrl = jsonObject.getString("downloadUrl"); // 下载链接

                        msg.what = CODE_READ_SUCCESS;
                    } else {
                        Log.i(TAG, "run: -->" + helper.responseCode());
                    }
                } catch (IOException e) {
                    // 网络错误
                    e.printStackTrace();
                    Log.i(TAG, "run: io exception");
                    msg.what = CODE_IO_ERROR;
                } catch (JSONException e) {
                    // json解析错误
                    e.printStackTrace();
                    msg.what = CODE_JSON_ERROR;
                } finally {
                    long endTime = System.currentTimeMillis();
                    long useTime = endTime - statTime;
                    Log.i(TAG, "run: use time = " + useTime);
                    if (useTime < DELAY) {
                        try {
                            Thread.sleep(DELAY - useTime); // 强制让闪屏界面显示两秒以上
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Log.i(TAG, "run: sleep ");
                        }
                    }

                    mHandler.sendMessage(msg);
                }
            }
        }.start();

//        thread.start();
    }

    /**
     * 显示升级对话框
     */
    void showUpdateDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).
                setTitle("发现新版本" + serverVersionName).
                setMessage(desc).
                setCancelable(true).
                setPositiveButton("现在升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        download();
                    }
                }).
                setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();// 对话框消失
                        enterHome(); //跳转到主界面
                        finish();
                    }
                }).
                setOnCancelListener(new DialogInterface.OnCancelListener() { // 当用户取消时
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        enterHome(); // 进入主页
                    }
                }).
                create();
        alertDialog.show();
    }

    /**
     * 下载apk
     */
    public void download() {
        Log.i(TAG, "download: 开始下载");

        try {
            new Thread() {
                @Override
                public void run() {
                    HttpConnectionHelper helper = new HttpConnectionHelper.Builder().
                            setRequestMethod(HttpConnectionHelper.POST_METHOD).
                            setConnectionTimeOut(5000).
                            setReadTimeOut(5000).
                            setPath(downloadUrl).
                            build();

                    Log.i(TAG, "run: url = " + downloadUrl);
                    InputStream inputStream = null;
                    OutputStream output = null;
                    try {
                        if (helper.isResponseOk()) {
                            Log.i(TAG, "run: -->" + "连接正常");
                            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //sd 卡挂在
                                File updateApk = new File(Environment.getExternalStorageDirectory(), "updateApk.apk"); //创建一个文件
                                inputStream = helper.getConnection().getInputStream();
                                output = new FileOutputStream(updateApk);
                                int len;
                                byte[] buffer = new byte[1024 * 2];
                                while ((len = inputStream.read(buffer)) != -1)
                                    output.write(buffer, 0, len);

                                Log.i(TAG, "run: -->" + "下载完毕");
                                output.flush();
                                helper.getConnection().disconnect();


                                // 跳转到系统下载页面
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setDataAndType(Uri.fromFile(updateApk), "application/vnd.android.package-archive");
                                // startActivity(intent);
                                startActivityForResult(intent, 0);// 如果用户取消安装的话,会返回结果,回调方法onActivityResult

                            } else {
                                Toast.makeText(SplashActivity.this, "未发现sd卡", Toast.LENGTH_SHORT).show();
                                Log.i(TAG, "run: 未发现sd卡, environment state= " + Environment.getExternalStorageState());
                            }
                        } else {
                            Log.i(TAG, "run: 响应码：" + helper.responseCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "run: io 错误");
                    } finally {
                        try {
                            if (output != null)
                                output.close();
                            if (inputStream != null)
                                inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } catch (NullPointerException e) {
            Log.i(TAG, "download: --> null");
        }
    }

    @Override
    public String toString() {
        return super.toString();
    }
}